package com.atmilan.quartz.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.atmilan.quartz.config.RestTemplateConfig;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class EuropeUtil {
    @Autowired
    RestTemplateConfig restTemplateConfig;
    private final String BASIC = "Basic {}";
    
    //递归查询所有商品数
    public static void getGoodsList(Integer pageNum, Integer num) throws Exception {

        String xml = "<tem:GetGoodsListByPage>" + "<tem:PageNum>" + pageNum + "</tem:PageNum>" + "<tem:PageSize>" + num + "</tem:PageSize>" + "</tem:GetGoodsListByPage>";

        String sendMsg = getSendMsg(xml);
        String respXml = getEuropeXml("BUYERCOO", "K3Hk5lEacEH8H", "http://studio69.atelier98.net/api_studio69/api_studio69.asmx", sendMsg);
        List<Map<String, Object>> list = STAXUtil.getEuropMapList(respXml, "GetGoodsListByPage");
        if (list.size() >= num) {//不是最后一页，继续查询
            pageNum++;
            System.out.println("pageNum:" + pageNum + "----------------------------------num:" + num + "-----Date" + new Date());
            getGoodsList(pageNum, num);
        } else {
            //是最后一页
            System.out.println("pageNum:" + pageNum + "----------------------------------num:" + num + "-----Date" + new Date());
        }
    }
    
    
    /**
     * 拼接请求报文
     * @param sendMsg
     * @return
     */
    public static String getSendMsg(String sendMsg) {
        String headXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">\n" + "<soapenv:Header />" + "<soapenv:Body>";
        String endXML = "</soapenv:Body>" + "</soapenv:Envelope>";
        String XML = headXML + sendMsg + endXML;
        return XML;
    }
    
    /**
     * 获取欧洲商品接口
     * @Description:  
     * @author daigb 
     * @param @param auth
     * @param @param url
     * @param @param msg
     * @param @return
     * @return String
     * @throws
     */
    public String getEuropeXmlNew(String auth, String url, String msg) {
        int i = 0;
        while(true) {
            if(i >= 2) {
                return null;
            }
            try {
                RestTemplate restTemplate = restTemplateConfig.restTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.TEXT_XML);
                headers.add("Authorization", StrUtil.format(BASIC, auth));
                HttpEntity<String> formEntity = new HttpEntity<>(msg, headers);
                ResponseEntity<String> response = restTemplate.postForEntity(url, formEntity , String.class);
                if(HttpStatus.OK == response.getStatusCode()) {
                    return response.getBody();
                } else {
                    i ++;
                    continue;
                }
            } catch (RestClientException e) {
                i ++;
                e.printStackTrace();
            }
        }
    }

    public static String getEuropeXml(String username, String password, String europeUrl, String sendMsg) throws IOException {
        int count = 1;
        while (true) {
            if(count >= 5) {
                return null;
            }
            String login = username + ":" + password;
            String encoding = Base64.encode(login.getBytes());
            InputStreamReader isr = null;
            BufferedReader inReader = null;
            StringBuffer result = null;
            OutputStream outObject = null;
            try {
                URL url = new URL(europeUrl);
                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                // 设置HTTP请求相关信息
                //设置超时
                httpConn.setConnectTimeout(120 * 1000);
                httpConn.setReadTimeout(120 * 1000);
                httpConn.setRequestProperty("Content-Length", String.valueOf(sendMsg.getBytes().length));
                httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
                httpConn.setRequestMethod("POST");
                httpConn.setDoOutput(true);
                httpConn.setDoInput(true);
                httpConn.setUseCaches(false);
                httpConn.setRequestProperty("Content-Type", "text/xml");
                httpConn.setRequestProperty("Authorization", "Basic " + encoding);
                // 进行HTTP请求
                outObject = httpConn.getOutputStream();
                outObject.write(sendMsg.getBytes());
                if (200 != (httpConn.getResponseCode())) {
                    // 关闭输出流
                    if (outObject != null) {
                        outObject.close();
                    }
                    count ++;
                    //返回数据异常继续请求
                    continue;
                }
                // 获取HTTP响应数据
                isr = new InputStreamReader(httpConn.getInputStream(), "utf-8");
                inReader = new BufferedReader(isr);
                result = new StringBuffer();
                String inputLine;
                while ((inputLine = inReader.readLine()) != null) {
                    result.append(inputLine);
                }
                return result.toString();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            } finally {
                // 关闭输入流
                if (inReader != null) {
                    inReader.close();
                }
                if (isr != null) {
                    isr.close();
                }
                // 关闭输出流
                if (outObject != null) {
                    outObject.close();
                }
            }
        }
    }
}
